package mamikeji.liaowa.ui.activity.right;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.RadioButton;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.umeng.analytics.MobclickAgent;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.FollowBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.activity.circle.FriendMSGActivity;
import mamikeji.liaowa.ui.adapter.Follow_MSGAdapter;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;
import mamikeji.liaowa.widget.pulltorefresh.PullToRefreshBase;
import mamikeji.liaowa.widget.pulltorefresh.PullToRefreshGridView;
import mamikeji.liaowa.widget.refreshView.PtrlDownRefreshFrameLayout;

/**
 * Created by 廉冲-android开发 on 2017/8/5.
 */
public class UserFollowActivity extends BaseActivity {
    private static final String TAG = "BabyMSGActicity";
    @BindView(R.id.radioButton_follow_guanzhu)
    RadioButton radioButtonFollowGuanzhu;
    @BindView(R.id.radioButton_follow_fans)
    RadioButton radioButtonFollowFans;
    @BindView(R.id.gridView_user_follow)
    PullToRefreshGridView gridViewUserFollow;
    @BindView(R.id.ptrlDownRefreshFrameLayout_follow)
    PtrlDownRefreshFrameLayout ptrlDownRefreshFrameLayoutFollow;
    @BindView(R.id.multiStateView_follow)
    MultiStateView multiStateViewFollow;

    private static final int TAG_CIRCLE = 1001;

    /**
     * true：关注
     * false：粉丝
     */
    private boolean bool_follow = false;

    private Follow_MSGAdapter follow_msgAdapter;
    private List<FollowBean.ListEntity> listEntityList = new ArrayList<>();
    private List<FollowBean.ListEntity> mList;

    /**
     * 请求的页数
     */
    private int page = 1;

    private String follow_code;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_follow);
        ButterKnife.bind(this);
        getBase();
        setTitleLeftBtn();
        String titleString = getResources().getString(R.string.follow_msg_title);
        String titleFinal = String.format(titleString, getIntent().getStringExtra(ForContents.USER_NAME));
        setTitleName(titleFinal);

        follow_code = getIntent().getStringExtra(ForContents.USER_follow);
        bool_follow = getIntent().getBooleanExtra("type", false);

        ForLog.i("bool_followbool_follow", "" + bool_follow);

        init();
        getFollowDate(1, 10);
    }

    private void init() {
        String guanzhuString = getResources().getString(R.string.follow_msg_guanzhu);
        String guanzhuFinal = String.format(guanzhuString, "0");
        radioButtonFollowGuanzhu.setText(guanzhuFinal);
        String fansString = getResources().getString(R.string.follow_msg_fensi);
        String fansFinal = String.format(fansString, "0");
        radioButtonFollowFans.setText(fansFinal);

        radioButtonFollowGuanzhu.setChecked(bool_follow);
        radioButtonFollowFans.setChecked(!bool_follow);

        follow_msgAdapter = new Follow_MSGAdapter(listEntityList, this);
        follow_msgAdapter.bool_follow = bool_follow;
        gridViewUserFollow.setAdapter(follow_msgAdapter);

        multiStateViewFollow.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiStateViewFollow.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        getFollowDate(1, 10);
                    }
                });
        ptrlDownRefreshFrameLayoutFollow.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, gridViewUserFollow.getRefreshableView(), header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getFollowDate(1, 10);
            }
        });
        gridViewUserFollow.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        gridViewUserFollow.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                //上拉加载更多
                getFollowDate(++page, 10);
            }
        });
        gridViewUserFollow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String code = bool_follow ? listEntityList.get(i).getFollowcode() : listEntityList.get(i).getUsercode();
                Intent mIntent = new Intent(UserFollowActivity.this, FriendMSGActivity.class);
                mIntent.putExtra(HttpKey.Friend_MSG_friendcode, code);
                startActivityForResult(mIntent, TAG_CIRCLE);
            }
        });
        follow_msgAdapter.setOnItemClickListener(new Follow_MSGAdapter.OnItemClickListener() {
            @Override
            public void onGuanzhuClick(String followCode, int position) {
                if (getJudgeLogin()) {
                    getGuanZhuCircle(followCode, position);
                }
            }
        });
    }

    @OnClick({
            R.id.radioButton_follow_guanzhu,
            R.id.radioButton_follow_fans
    })
    public void onViewClicked(View view) {
        radioButtonFollowGuanzhu.setChecked(false);
        radioButtonFollowFans.setChecked(false);
        switch (view.getId()) {
            case R.id.radioButton_follow_guanzhu:
                radioButtonFollowGuanzhu.setChecked(true);
                bool_follow = true;
                follow_msgAdapter.bool_follow = bool_follow;
                getFollowDate(1, 10);
                break;
            case R.id.radioButton_follow_fans:
                radioButtonFollowFans.setChecked(true);
                bool_follow = false;
                follow_msgAdapter.bool_follow = bool_follow;
                getFollowDate(1, 10);
                break;
        }
    }

    private void getFollowDate(final int indexpage, final int pagesize) {
        showLoading();
        Map<String, String> formMap = new HashMap<>();
        formMap.put(HttpKey.Follow_msg_USERCODE, follow_code);
        formMap.put(HttpKey.Follow_msg_USERCODE_1, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.Follow_msg_pageSize, pagesize + "");
        formMap.put(HttpKey.Follow_msg_pageIndex, indexpage + "");

        String url = HttpApi.ROOT_PATH + (bool_follow ? HttpApi.Follow_guanzhu : HttpApi.Follow_fans);

        ForHttp.setMsg(url, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
                multiStateViewFollow.setViewState(MultiStateView.VIEW_STATE_NOINTERNET);
                ptrlDownRefreshFrameLayoutFollow.refreshComplete();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                gridViewUserFollow.onRefreshComplete();
                ptrlDownRefreshFrameLayoutFollow.refreshComplete();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        FollowBean followBean = new Gson().fromJson(response, FollowBean.class);
                        mList = followBean.getList();

                        if (followBean.getFocusCount() != 0 || followBean.getFansCount() != 0) {
                            String guanzhuString = getResources().getString(R.string.follow_msg_guanzhu);
                            String guanzhuFinal = String.format(guanzhuString, followBean.getFocusCount() + "");
                            radioButtonFollowGuanzhu.setText(guanzhuFinal);
                            String fansString = getResources().getString(R.string.follow_msg_fensi);
                            String fansFinal = String.format(fansString, followBean.getFansCount() + "");
                            radioButtonFollowFans.setText(fansFinal);
                        }

                        if (mList != null && mList.size() > 0) {
                            if (mList.size() <= 0) {
                                new Handler().postDelayed(new Runnable() {
                                    public void run() {
                                        gridViewUserFollow.onRefreshComplete();
                                    }
                                }, 1000);
                                ForToast.showToast(R.string.error_down_end);
                            } else {
                                if (indexpage == 1) {
                                    listEntityList.clear();
                                    listEntityList.addAll(mList);
                                    follow_msgAdapter.setList(listEntityList);
                                } else {
                                    listEntityList.addAll(mList);
                                    follow_msgAdapter.notifyDataSetChanged();
                                }
                            }
                            multiStateViewFollow.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        } else {
                            if (indexpage == 1)
                                multiStateViewFollow.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                        }
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                        multiStateViewFollow.setViewState(MultiStateView.VIEW_STATE_ERROR);
                    }
                    hideLoading();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 关注朋友
     */
    public void getGuanZhuCircle(final String followusercode, final int position) {
        showLoading();
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.Follow_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.Follow_followusercode, followusercode);
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.FRIEND_MSG_follow, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                hideLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        int date = Integer.parseInt(jsonObject.getString("data"));
                        if (bool_follow) {
                            if (ForPreference.getString(ForContents.USER_CODE).equals(follow_code)) {
                                listEntityList.remove(position);
                            } else {
                                listEntityList.get(position).setAfollow(date);
                            }
                        } else {
                            listEntityList.get(position).setAfollow(date);
                        }

                        int follow = ForPreference.getInt(ForContents.USER_follow);//关注数
                        switch (date) {
                            case 1:
                                ForPreference.putInt(ForContents.USER_follow, ++follow);
                                break;
                            case 2:
                                ForPreference.putInt(ForContents.USER_follow, --follow);
                                break;
                            case 3:
                                ForPreference.putInt(ForContents.USER_follow, ++follow);
                                break;
                        }
                        if (ForPreference.getString(ForContents.USER_CODE).equals(follow_code)){
                            String numString = getResources().getString(R.string.follow_msg_guanzhu);
                            String numFinal = String.format(numString, ForPreference.getInt(ForContents.USER_follow) + "");
                            radioButtonFollowGuanzhu.setText(numFinal);
                        }
                        follow_msgAdapter.notifyDataSetChanged();
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("粉丝与关注");
        MobclickAgent.onResume(this);       //开始统计时长
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("粉丝与关注");
        MobclickAgent.onPause(this);       //结束统计时长
    }
}
